<?php
define("TITLE_TAG", "---\ntitle: ");
define("END_TITLE_TAG","\noutput:\n");
define("MARKDOWN_TAG","tutorial::go_interactive()\n```\n");
define("INSTRUCTIONS_TAG", "\n*** =instructions\n");
define("HINT_TAG", "\n*** =hint\n");
define("PRE_CODE_TAG", "\n```{r ex=\"create_a\", type=\"pre-exercise-code\"}\n");
define("SAMPLE_CODE_TAG", "\n```{r ex=\"create_a\", type=\"sample-code\"}\n");
define("SOLUTION_TAG", "\n```{r ex=\"create_a\", type=\"solution\"}\n");
define("SCT_TAG", "\n```{r ex=\"create_a\", type=\"sct\"}\n");
define("CODE_END_TAG",  "\n```\n");



function strcut($txt,$start,$end){
	return substr($txt,$start,$end-$start);
}



class RmdParser{

	private $title,$markdown,$hints,$pre_code,$sample_code,$solution,$sct;

	public  function __construct($path){
		$txt = file_get_contents($path);
		$titleIdx = strpos($txt, TITLE_TAG);
		$endTitleIdx = strpos($txt, END_TITLE_TAG);
	 	$markdownIdx =   strpos($txt,MARKDOWN_TAG);
	    $instructionsIdx = strpos($txt, INSTRUCTIONS_TAG);
	    $hintIdx = strpos($txt, HINT_TAG);
	    $precodeIdx = strpos($txt, PRE_CODE_TAG);
	    $this->title = strcut($txt,$titleIdx + strlen(TITLE_TAG),$endTitleIdx);
	    $this->markdown = strcut($txt,$markdownIdx + strlen(MARKDOWN_TAG), $instructionsIdx);
	    $instructions = strcut($txt,$instructionsIdx + strlen(INSTRUCTIONS_TAG), $hintIdx);
	    $this->hints = strcut($txt,$hintIdx + strlen(HINT_TAG), $precodeIdx);
	    $txt = substr($txt,$precodeIdx);//
	    $endCodeIdx = strpos($txt,CODE_END_TAG);//结束标签
	    $this->pre_code = strcut($txt,strlen(PRE_CODE_TAG), $endCodeIdx);	   
        $sampleCodeIdx = strpos($txt,SAMPLE_CODE_TAG);
        $txt = substr($txt,$sampleCodeIdx + strlen(SAMPLE_CODE_TAG));//截取到sample_code 开头
        $endCodeIdx = strpos($txt,CODE_END_TAG);
        $this->sample_code =  substr($txt,0, $endCodeIdx);
        $solutionIdx = strpos($txt,SOLUTION_TAG);
        $txt = substr($txt,$solutionIdx + strlen(SOLUTION_TAG));//截取至solution 开头
        $endCodeIdx = strpos($txt,CODE_END_TAG);
        $this->solution = substr($txt,0, $endCodeIdx);
        $sctIdx = strpos($txt,SCT_TAG);
        $txt = substr($txt,$sctIdx + strlen(SCT_TAG));//截取至 sct 开头
        $this->sct = substr($txt,0, $sctIdx);
	}

	public function getTitle()
	{
		return $this->title;
	}

	public function getMarkdown()
	{
		return $this->markdown;
	}

	public function getHints()
	{
		return $this->hints;
	}

	public function getSolution()
	{
		return $this->solution;
	}

	public function getPreCode()
	{
		return $this->pre_code;
	}

	public function getSampleCode()
	{
		return $this->sample_code;		
	}

	public function getSct()
	{
		return $this->sct;
	}
}
